<?php

namespace addons\mplogin\model;

use think\Log;
use think\Model;
use think\Request;

class Bind extends Model
{
    // 表名
    protected $name = 'mplogin_bind';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];

    public static function bind($openid, $admin_id)
    {
        $find = self::getAdmin($openid);
        if ($find) {
            $find->admin_id = $admin_id;
            $find->save();
            return $find;
        } else {
            Log::write("扫码登录--绑定openid:{$openid}---{$admin_id}---".CAIJIAKU_ID);
            return self::create([
                "admin_id"  => $admin_id,
                "mp_openid" => $openid,
                "caijiakuid" => CAIJIAKU_ID,
            ]);
        }
    }

    public static function getAdmin($openid)
    {
        return self::get(["mp_openid" => $openid,"caijiakuid" => CAIJIAKU_ID]);
    }

    public function admin()
    {
        return $this->hasOne("Admin", "id", "admin_id")->field("id,username,nickname,password,avatar");
    }

    public static function getOpenid($admin_id)
    {
        return self::get(["admin_id" => $admin_id]);
    }
}
